package org.example;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import rx.annotations.Beta;

@SpringBootApplication
@EnableDiscoveryClient  // 启用 Eureka 客户端
@EnableHystrixDashboard  // 启用 Hystrix Dashboard
@EnableHystrix
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class);
    }

    @Bean
    public ServletRegistrationBean getServlet(){
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(streamServlet);
        servletRegistrationBean.setLoadOnStartup(1);
        servletRegistrationBean.addUrlMappings("/hystrix.stream");
        servletRegistrationBean.setName("hystrix");
        return servletRegistrationBean;
    }
    @RestController
    class DemoController {

        @GetMapping("/hello")
        public String sayHello() {
            return "Hello, World!";
        }

        @GetMapping("/fail")
        @HystrixCommand(fallbackMethod = "fallbackHello")
        public String failService() {
            // 模拟服务失败
            if (Math.random() > 0.5) {
                throw new RuntimeException("Service failure");
            }
            return "Service is working";
        }

        // Hystrix 回退方法
        public String fallbackHello() {
            return "Service is unavailable, please try again later!";
        }
    }
}